import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { getRoleList, getRoleMenu, getRoleMenuIds, saveRole, updateRole ,deleteRole, saveRoleMenu, updateRoleStatus} from "@/api/system/role";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";

export function useRole(treeRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    status: "",
    currentPage: 1,
      pageSize: 10
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "id"
    },
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "角色标识",
      prop: "code"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 160
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  // const buttonClass = computed(() => {
  //   return [
  //     "!h-[20px]",
  //     "reset-margin",
  //     "!text-gray-500",
  //     "dark:!text-white",
  //     "dark:hover:!text-primary"
  //   ];
  // });

   function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
    .then(async () => {
        // 开始加载状态
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );

        // 准备更新数据
        const updatedRow = {
            id: row.id,
            status: row.status 
        };


        // 调用更新接口
        try {
            const result = await updateRoleStatus(updatedRow );
            if (result.success) {
                // 更新成功，设置新状态
                row.status = updatedRow.status;
                message("已成功修改用户状态", { type: "success" });
            } else {
                // 更新失败，回滚状态
                row.status = row.status === 0 ? 1 : 0;
                message(`更新失败: ${result.info || '未知错误'}`, { type: "error" });
            }
        } catch (error) {
            // 异常处理，回滚状态
            row.status = row.status === 0 ? 1 : 0;
            message(`更新异常: ${error.message}`, { type: "error" });
        }

        // 结束加载状态
        setTimeout(() => {
            switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                    loading: false
                }
            );
        }, 300);

    }).catch(() => {
        // 用户取消操作，回滚状态
        row.status = row.status === 0 ? 1 : 0;
    });
  }

async function handleDelete(row) {
  try {
    // 检查 row 是否有有效的 id
    if (!row || !row.id) {
      throw new Error('ID不能为空!');
    }

    // 假设 deleteUser 函数接受一个 ID，并返回一个 Promise
    const result = await deleteRole(row);
    
    // 判断 deleteUser 函数的执行结果
    if (result.success) {
      // 如果删除成功，显示成功消息
      message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    } else {
      // 如果删除失败，根据返回的 info 显示错误消息
      throw new Error(result.info || '删除失败，未知错误');
    }
    
    // 重新搜索更新列表
    onSearch();
  } catch (error) {
    // 显示错误消息
    message(`删除用户编号为${row.id}的数据失败: ${error.message}`, { type: "error" });
  }
}
 /** 菜单权限-保存 */
  function handleSave() {
      const { id, name } = curRow.value;
      const checkedKeys = treeRef.value.getCheckedKeys();
      
      // 合并 id 和 checkedKeys
      const payload = {
        roleId: id,
        menuIds: checkedKeys
      };
    // 根据用户 id 调用实际项目中菜单权限修改接口
    saveRoleMenu(payload)
      .then(response => {
        if (response.success) {
          message(`角色名称为${name}的菜单权限修改成功: ${response.info}`, {
            type: "success"
          });
        } else {
          message(`角色名称为${name}的菜单权限修改失败: ${response.info}`, {
            type: "error"
          });
        }
      })
      .catch(error => {
        message(`角色名称为${name}的菜单权限修改失败：${error.message}`, {
          type: "error"
        });
      });
    
  }

   function handleSizeChange(val: number) {
  
   pagination.pageSize = val;
   form.pageSize = val;
  onSearch(); // 重新加载数据
}

 function handleCurrentChange(val: number) {
  
   pagination.currentPage = val;
   form.currentPage = val;
  onSearch(); // 重新加载数据
}
  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getRoleList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          name: row?.name ?? "",
          code: row?.code ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
         FormRef.validate(async valid => {
                if (valid) {
                   
                        let result;
                        // 表单规则校验通过
                        if (title === "新增") {
                            result = await handleCreate(curData);
                        } else {
                            result = await handleUpdate(row, curData);
                  }
                  console.log(result)
                        if (result.success) {
                            chores();
                        } else {
                            message(`操作失败: ${result.info || '未知错误'}`, { type: "error" });
                        }
                    
                }
            });
      }
    });
  }
  async function handleCreate(row) {
    try {
        // 检查 row 是否为空
        if (!row) {
            throw new Error('数据对象不能为空!');
        }
        // 假设 saveUser 函数接受一个 row 对象，并返回一个 Promise
        const result = await saveRole(row);
        
        // 判断 saveUser 函数的执行结果
        if (result.success) {
            // 重新搜索更新列表
          onSearch();
          return { success: true }; // 返回成功状态
        } else {
            // 如果保存失败，根据返回的信息显示错误消息
            throw new Error(result.info || '创建失败，未知错误');
        }
        
    } catch (error) {
        // 显示错误消息
        message(`创建用户失败: ${error.message}`, { type: "error" });
         return { success: false, info: error.message }; // 返回失败状态和错误信息
    }
  }
  async function handleUpdate(row, afterRow) {
    try {
        // 检查 row 是否有有效的 id
        if (!row || !row.id) {
            throw new Error('数据对象不能为空且必须包含 id!');
        }

        // 合并 row 和 afterRow，确保 id 被包含
        const updatedRow = {
            ...afterRow, // 先展开 afterRow 以避免覆盖 row 中的 id
            id: row.id   // 显式确保 id 存在
        };

        // 假设 updateUser 函数接受一个 row 对象，并返回一个 Promise
        const result = await updateRole(updatedRow);
        
        // 判断 updateUser 函数的执行结果
        if (result.success) {
            // 如果更新成功，显示成功消息
            message(`您成功更新了用户编号为${row.id}的这条数据`, { type: "success" });
            // 重新搜索更新列表
          onSearch();
            return { success: true }; // 返回成功状态
        } else {
            // 如果更新失败，根据返回的 info 显示错误消息
            throw new Error(result.info || '更新失败，未知错误');
        }
        
    } catch (error) {
        // 显示错误消息
      message(`更新用户编号为${row.id}的数据失败: ${error.message}`, { type: "error" });
       return { success: false, info: error.message }; // 返回失败状态和错误信息
    }
  }

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { id } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      const { data } = await getRoleMenuIds({ id });
      treeRef.value.setCheckedKeys(data);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    const { data } = await getRoleMenu();
    treeIds.value = getKeyList(data, "id");
    treeData.value = handleTree(data);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleSave,
    handleMenu,
    handleCreate,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
